using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Workflow.Activities;
using System.Collections.ObjectModel;
using System.Workflow.Runtime;

namespace Incubator.OTWorkflow.Client
{
    public partial class Form1 : Form
    {
        delegate void UpdateUIDelegate(string id);

        OTWorkflowRunner runner;
        OTStateService s;

        public Form1()
        {
            InitializeComponent();
            s = new OTStateService(); 
            runner = new OTWorkflowRunner(s);
            runner.OnWorkflowIdled += new EventHandler<WorkflowEventArgs>(runner_OnWorkflowIdled);
            runner.OnWorkflowCompleted += new EventHandler<WorkflowEventArgs>(runner_OnWorkflowCompleted);            
        }

        #region ListView Accessors
        string SelectedOt
        {
            get
            {
                string result = string.Empty;
                if (listViewOTS.SelectedItems.Count == 0)
                {
                    result = listViewOTS.Items[0].SubItems[1].Text;
                }
                else
                {
                    result = listViewOTS.SelectedItems[0].SubItems[1].Text;
                }
                return result;
            }
        }

        Guid SelectedInstanceId
        {
            get
            {
                Guid result = Guid.Empty;
                if (listViewOTS.SelectedItems.Count == 0)
                {
                    result = new Guid(listViewOTS.Items[0].SubItems[0].Text);
                }
                else
                {
                    result = new Guid(listViewOTS.SelectedItems[0].SubItems[0].Text);
                }
                return result;
            }
        }

        #endregion
                
        #region WorkflowEvents
        void runner_OnWorkflowIdled(object sender, WorkflowEventArgs e)
        {
            UpdateListViewByInstance(e.WorkflowInstance.InstanceId.ToString());
        }

        void runner_OnWorkflowCompleted(object sender, WorkflowEventArgs e)
        {
            UpdateListViewByInstanceToComplete(e.WorkflowInstance.InstanceId.ToString());
        }

        void UpdateListViewByInstance(string instance)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new UpdateUIDelegate(this.UpdateListViewByInstance), new object[1] { instance });
            }
            else
            {
                ListViewItem item = listViewOTS.Items[instance];
                string codOt = item.SubItems[1].Text;
                item.SubItems[2].Text = runner.GetCurrentState(codOt);
                item.SubItems[3].Text = "Running";
                item.Selected = true;
                //EnableButtonsByOtState(codOt);
            }
        }

        void UpdateListViewByInstanceToComplete(string instance)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new UpdateUIDelegate(this.UpdateListViewByInstanceToComplete), new object[] { instance });
            }
            else
            {
                ListViewItem item = listViewOTS.Items[instance];
                string codOt = item.SubItems[1].Text;
                item.SubItems[2].Text = runner.GetCurrentState(codOt);
                item.SubItems[3].Text = "Complete";
                item.Selected = true;
                //EnableButtonsByOtState(codOt);
            }
        }
        
        #endregion
        
        #region ButtonsClick

        private void buttonCreate_Click(object sender, EventArgs e)
        {
            Guid id = runner.InitializeStateMachine(textBoxCodigoOT.Text);

            ListViewItem item = this.listViewOTS.Items.Add(id.ToString(), id.ToString(), "");
            item.SubItems.Add(textBoxCodigoOT.Text);
            item.SubItems.Add("...");
            item.SubItems.Add("Started");
            item.Tag = id;
            item.Selected = true;

            textBoxCodigoOT.Text = (Convert.ToInt32(textBoxCodigoOT.Text) + 1).ToString();
        }

        private void buttonCreateOtEnCurso_Click(object sender, EventArgs e)
        {
            Guid id = runner.CreateOtStateEnCurso(textBoxCodigoOT.Text);

            ListViewItem item = this.listViewOTS.Items.Add(id.ToString(), id.ToString(), "");
            item.SubItems.Add(textBoxCodigoOT.Text);
            item.SubItems.Add("...");
            item.SubItems.Add("Started");
            item.Tag = id;
            item.Selected = true;

            textBoxCodigoOT.Text = (Convert.ToInt32(textBoxCodigoOT.Text) + 1).ToString();
            
        }

        private void buttonCreateOtAsignada_Click(object sender, EventArgs e)
        {
            Guid id = runner.CreateOtStateAsignada(textBoxCodigoOT.Text);

            ListViewItem item = this.listViewOTS.Items.Add(id.ToString(), id.ToString(), "");
            item.SubItems.Add(textBoxCodigoOT.Text);
            item.SubItems.Add("...");
            item.SubItems.Add("Started");
            item.Tag = id;
            item.Selected = true;

            textBoxCodigoOT.Text = (Convert.ToInt32(textBoxCodigoOT.Text) + 1).ToString();
        }
        
        private void buttonAsignar_Click(object sender, EventArgs e)
        {
            try
            {
                s.RaiseOTAsignadaEvent(SelectedInstanceId, SelectedOt);
            }
            catch (EventDeliveryFailedException ex)
            {
                DebugMsg(ex.ToString());

            }
        }

        private void buttonIniciar_Click(object sender, EventArgs e)
        {
            try
            {
                s.RaiseOTIniciadaEvent(SelectedInstanceId, SelectedOt);
            }
            catch (EventDeliveryFailedException ex)
            {
                DebugMsg(ex.ToString());

            }
        }

        private void buttonFinalizar_Click(object sender, EventArgs e)
        {
            try
            {
                s.RaiseOTFinalizadaEvent(SelectedInstanceId, SelectedOt);
            }
            catch (EventDeliveryFailedException ex)
            {
                DebugMsg(ex.ToString());

            }
        }

        #endregion                 
 
        #region ListView Selection
        private void listViewOTS_SelectedIndexChanged(object sender, EventArgs e)
        {

            ListView lv = (ListView)sender;
            if (lv.SelectedItems.Count > 0)
            {
                string selectedOt = lv.SelectedItems[0].SubItems[1].Text;
                //EnableButtonsByOtState(selectedOt);
            }
        }

        void EnableButtonsByOtState(string codOt)
        {
            string nextState = runner.GetNextState(codOt);
            EnableDisableButtons(nextState);
        }

        private void EnableDisableButtons(string nextState)
        {
            buttonAsignar.Enabled = false;
            buttonIniciar.Enabled = false;
            buttonFinalizar.Enabled = false;

            if (nextState.Equals("OTAsignada")) buttonAsignar.Enabled = true;
            if (nextState.Equals("OTEnCurso")) buttonIniciar.Enabled = true;
            if (nextState.Equals("OTFinalizada")) buttonFinalizar.Enabled = true;

        }

        #endregion

        #region Debug
        void DebugMsg(string msg)
        {
            textBox1.Text += msg + "\r\n";
            textBox1.Select(textBox1.Text.Length - 1, 1);
            textBox1.ScrollToCaret();
        } 
        #endregion        


    }
}